package com.zjm.behavioral.interpreter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 表达式求值
 */
public class ClientTest {
    public static void main(String[] args) throws IOException {
        String expStr = getExpStr();
        Map<String, Integer> var = getValue(expStr);
        Calculator calculator = new Calculator(expStr);
        System.out.println("运算结果：" + expStr + "=" + calculator.run(var));

    }


    public static String getExpStr() throws IOException {
        System.out.print("请输入表达式：");
        return (new BufferedReader(new InputStreamReader(System.in))).readLine();
    }

    public static Map<String, Integer> getValue(String expStr) {
        Map<String, Integer> map = new HashMap<>();
        for (char ch : expStr.toCharArray()) {
            if (ch != '+' && ch != '-' && ch != '*' && ch != '/') {
                // 如果字符是字母且还没有赋值，则提示用户输入值
                if (Character.isLetter(ch) && !map.containsKey(String.valueOf(ch))) {
                    System.out.print("请输入变量 " + ch + " 的值：");
                    try {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                        int value = Integer.parseInt(reader.readLine());
                        map.put(String.valueOf(ch), value);
                    } catch (IOException | NumberFormatException e) {
                        System.out.println("输入错误，使用默认值0");
                        map.put(String.valueOf(ch), 0);
                    }
                }
            }
        }
        return map;
    }
}
